global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/Table_A32_excluding_countries.log, replace name(tabl)

capture noi { 

	
	* use global country_list "AU AT BE BG BR CA CH CN CY CZ DE DK ES EE FI FR GB GR HU ID IN IE IT JP KR LT LU LV MX MT NL PL PT RO RU SK SI SE TR TW US" as check
	*can be run with any number of combinations, as long as the weights are built for (respectively without) the countries in the list. 6 countries means 6 sets of weights... takes a bit
	global country_list "US DE JP GB FR IT ES" 

	* Extract average weight from baseline regression firms, store as local for reg in separate txt
	use ${final_dir}/bvd_list_regfirms_auto95.dta, clear
	mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_tfacit1.dta, unmatched(master)
	foreach ctry of global country_list {
		egen avg_weight`ctry' = mean(share2_all_1995_`ctry')
		quietly su avg_weight`ctry'
		local avgwt_`ctry': di %10.2f `r(mean)'
	}
	keep BvD avg*
	reshape long avg_weight, i(BvD) j(country, string)
	drop BvD
	duplicates drop
	gsort -avg_weight
	cap log using ${numb_dir}/Table_A32_excl_countries_avgweights_numbers.log, replace name(avgw)
	list, noobs ab(12) clean
	cap log close avgw

	* Prepare regressions (variables that stay across specifications)
	estimates clear
	use ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear
	mmerge BvD year using ${dataset_dir}/indep_vars/bvd_year_indepvars_sharesgdpweighted_excluding_final_tfacit1.dta, unmatched(master)
	drop _m
	tab year, gen(YY_)
	clonevar spilloversown = spill${depvar}${ttt}_1995_a
	clonevar spilloversother = spillN${depvar}${ttt}_1995_a
	clonevar spilloversownzero = spill${depvar}${ttt}_1995_a0
	clonevar spilloversotherzero = spillN${depvar}${ttt}_1995_a0
	clonevar stockown = k${depvar}_${ttt} 
	clonevar stockownzero = k${depvar}_${ttt}0  
	clonevar stockother = kNOT_${depvar}_${ttt} 
	clonevar stockotherzero = kNOT_${depvar}_${ttt}0
	bys lse_id : egen _total_${depvar}_${ttt}_1995 = sum(${depvar}_${ttt}) if year>=1995+2 & year <= 2009+2
	bys lse_id : egen total_${depvar}_${ttt}_1995 = max(_total_${depvar}_${ttt}_1995)
	drop _total_${depvar}_${ttt}_1995
	egen yearctry = group(year country_shr_1995) if year <= 2009
	egen yearindustry = group(year industry) if year <= 2009
	egen yearctryindustry = group(year industry country_shr_1995) if year <= 2009
	sort lse_id year

	* Run foreign baseline (i.e., "none" excluded) as first column
	clonevar LSW_foreign = lswMPm_shr4_foreign_1995_a
	clonevar HSW_foreign = hswMPm_shr4_foreign_1995_a
	clonevar GDPgap_foreign = lngdpgap_shr_foreign_1995_a
	clonevar GDPPC_foreign = gdppcMPm_shr4_foreign_1995_a	
	clonevar VAEMP_foreign = vaempMPm_shr4_foreign_1995_a

	ppmlhdfe F2.${depvar}_${ttt} LSW_foreign HSW_foreign GDPgap_foreign VAEMP_foreign stockown stockownzero stockother stockotherzero spilloversown spilloversownzero spilloversother spilloversotherzero if year>=1995 & missing_weights_1995 ==0 & missing_spill_weights_1995 == 0 & maxweight_1995 < 1 & total_${depvar}_${ttt}_1995>0, vce(cluster lse_id)  absorb(lse_id yearctry yearindustry)
	estadd local has_stockspill "\yes"
	estadd local f "\yes"
	estadd local iy "\yes"
	estadd local cy "\yes"
	estadd local ctw "\no"
	estadd local obs "{\num{`e(N)'}}"
	estadd local firms "{\num{`e(N_clust)'}}"
	estimates store col_0

	* Run foreign regressions excluding one country at a time
	foreach ctry of global country_list {
		* Build a excluded-country weight * times year dummy variable
		mmerge BvD using ${dataset_dir}/weights/bvdid_pat_weights_EPtr_from1970_1995_orbis2017_${wtype}.dta, unmatched(master) ukeep(share2_all_1995_`ctry')
		forvalues i = 1995(1)2009 {
			gen YY_`i' = 1 if year == `i' 
			replace YY_`i' = 0 if YY_`i' ==. 
			gen cweight_year`i' = share2_all_1995_`ctry' * YY_`i'
			drop YY_`i'
		}
		* Prepare the generated vars
		replace LSW_foreign = lswMPm_shr4_fg_excl`ctry'_a	
		replace HSW_foreign = hswMPm_shr4_fg_excl`ctry'_a	
		replace GDPgap_foreign = lngdpgap_shr_fg_excl`ctry'_a
		replace GDPPC_foreign =  gdppcMPm_shr4_fg_excl`ctry'_a	
		replace VAEMP_foreign = vaempMPm_shr4_fg_excl`ctry'_a	

		* Run regs
		sort lse_id year	
		ppmlhdfe F2.${depvar}_${ttt} LSW_foreign HSW_foreign GDPgap_foreign VAEMP_foreign stockown stockownzero stockother stockotherzero spilloversown spilloversownzero spilloversother spilloversotherzero cweight_year* if year>=1995 & missing_weights_1995 ==0 & missing_spill_weights_1995 == 0 & maxweight_1995 < 1 & total_${depvar}_${ttt}_1995>0, vce(cluster lse_id)  absorb(lse_id yearctry yearindustry)
		estadd local has_stockspill "\yes"
		estadd local f "\yes"
		estadd local iy "\yes"
		estadd local cy "\yes"
		estadd local ctw "\yes" 
		estadd local obs "{\num{`e(N)'}}"
		estadd local firms "{\num{`e(N_clust)'}}"
		estimates store col_`ctry'
		su share2_all_1995_`ctry' if e(sample)==1 // Note: this is the average weight in the sample of the excluding regression. Average baseline weight calculated above.
		drop cweight_year*
	}

	do ${code_dir}/config/tabletools.do
	setlabels 

	dhoztab * using ${tab_dir}/appendix/Table_A32_excluding_countries.tex, b(%10.2f) se(%10.2f) nogaps replace nonumbers mlabel("(0)" "(1)" "(2)" "(3)" "(4)" "(5)" "(6)" "(7)")  nonotes nolines nomtitles sfmt(a1) scalars("ctw \noalign{\medskip} Excluded country weight \stimes year dummy" "has_stockspill Stocks and spillovers" "f Firm fixed effects" "iy Industry \stimes year fixed effects" "cy Country \stimes year fixed effects" "obs \noalign{\medskip} Observations"  "firms Number of firms") label drop(*zero _cons spill* stock* cweight_year*) noobs rename(LSW_foreign LSW HSW_foreign HSW GDPgap_foreign GDPGAP VAEMP_foreign VAEMP GDPPC_foreign GDPPC) substitute(\_ _) ///
	rawaddheader({Excluded country} & {None} & {US} & {DE} & {JP} & {GB} & {FR} & {IT} & {ES} \\ {Average weight} & & {`avgwt_US'} & {`avgwt_DE'} & {`avgwt_JP'} & {`avgwt_GB'} & {`avgwt_FR'} & {`avgwt_IT'} & {`avgwt_ES'} \\) ///
		depvar("Auto95") refcat(LSW "Foreign:", nolabel) ///
		notes("This table excludes one country at the time. Column 0 reproduces the baseline regression with normalized foreign wages. Columns 1--7 exclude the country in the column header in addition to the domestic country when computing the normalized foreign macroeconomic variables. Additionally, columns 1--7 control for the weight of the excluded country times year dummies. The average weight in the header reports the average country weight for the firms in the sample of column 1. All columns include firm, industry-year and country-year fixed effects. Standard errors are clustered at the firm-level and reported in parentheses.")
}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}